package com.sz.stock.controller;

import com.alibaba.fastjson.JSON;
import com.sz.stock.commons.HttpClientUtil;
import com.sz.stock.commons.ResultBean;
import com.sz.stock.model.Stock;
import com.sz.stock.model.StockOhcl;
import com.sz.stock.model.StockStopPoint;
import com.sz.stock.service.IStockOhclService;
import com.sz.stock.service.IStockService;
import com.sz.stock.service.IStockStopPointService;
import com.sz.stock.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/stock")
public class StockController {
    @Autowired
    private IStockService stockService;
    @Autowired
    private IStockOhclService stockOhclService;
    @Autowired
    private IStockStopPointService stockStopPointService;
    @Autowired
    private RedisUtil redisUtil;


    @RequestMapping("/say")
    public String sayHello() {
        return "hello";
    }

    @RequestMapping("/test")
    public ResultBean testService() {
        return new ResultBean(0, "测试服务调用!", null);
    }
    @RequestMapping("/testparam")
    public ResultBean testparamService(String name, String pwd) {
        return new ResultBean(0, name, pwd);
    }

    /**
     * 分时段获取股票当前信息
     * @param code
     * @param scale
     * @param datalen
     * @return 返回json数据：day日期、open开盘价、high最高价、low最低价、close收盘价、volume成交量；向前复权的数据
     */
    @RequestMapping("/getMarketData")
    public ResultBean getMarketData(String code, String scale, String datalen) {
        String url = "http://money.finance.sina.com.cn/quotes_service/api/json_v2.php/CN_MarketData.getKLineData?symbol=" + code + "&scale=" + scale + "&ma=no&datalen=" + datalen;
        String result = HttpClientUtil.getMethod(url);
        if (null == result || "null".equals(result)) {
            return new ResultBean(101, "找不到资源", result);
        } else {
            return new ResultBean(0, "success", JSON.parse(result));
        }
    }

    /**
     * 查询全部证券的基本信息
     * */
    @RequestMapping("/getAllStock")
    public ResultBean getAllStock() {
        List<Stock> list = stockService.getAll();
        if (null != list && list.size() > 0) {
            return new ResultBean(0, "success", list);
        } else {
            return new ResultBean(0, "暂无数据", list);
        }
    }

    /**
     * 从新浪接口获取当前的股票行情
     * @param code kk
     * @return
     * JSON实时数据，以逗号隔开相关数据，数据依次是“
     * 股票名称、今日开盘价、昨日收盘价、当前价格、今日最高价、今日最低价、
     * 竞买价、竞卖价、成交股数、成交金额、
     * 买1手、买1报价、买2手、买2报价、…、买5报价、…、卖5报价、
     * 日期、时间
     */
    @RequestMapping("/getStockDate")
    public ResultBean getStockDate(String code) {
        String url = "http://hq.sinajs.cn/list=" + code;
        String method = HttpClientUtil.getMethod(url);
        return new ResultBean(0, "success", null);
    }

    @RequestMapping("/getStock")
    public ResultBean getStock(@RequestBody String code){
        List<Stock> one = stockService.getOne(code);
        if (one.size() != 0) {
            Stock stock=one.get(0);
            return new ResultBean(0, "查询成功!", stock);
        } else {
            return new ResultBean(-1, "查询失败!", null);
        }
    }

    @RequestMapping("/getStock1")
    public Stock getStock1(@RequestBody String code){
        List<Stock> one = stockService.getOne(code);
        if (one.size() != 0) {
            Stock stock=one.get(0);
            return stock;
        } else {
            return null;
        }
    }

    /*=====Ohcl操作=====*/
    @RequestMapping("/getAllOhcl")
    public ResultBean getAllOhcl() {
        List<StockOhcl> list = stockOhclService.getAll();
        return new ResultBean(0, "查询成功!", list);
    }

    @RequestMapping("/getOneOhcl")
    public ResultBean getOneOhcl(@RequestBody String code){
        StockOhcl stockOhcl = stockOhclService.getOne(code);
        if (stockOhcl != null) {
            return new ResultBean(0, "查询成功!", stockOhcl);
        } else {
            return new ResultBean(-1, "查询失败!", stockOhcl);
        }
    }

    /*=====StopPoint操作=====*/
    @RequestMapping("/getOneStopPoint")
    public ResultBean getOneStopPoint(@RequestBody String code){
        StockStopPoint stockStopPoint = stockStopPointService.getOne(code);
        if (stockStopPoint != null) {
            return new ResultBean(0, "查询成功!", stockStopPoint);
        } else {
            return new ResultBean(-1, "查询失败!", stockStopPoint);
        }
    }

    @RequestMapping("/getAllStopPoint")
    public ResultBean getOneStopPoint() {
        return new ResultBean(0, "查询成功!", stockStopPointService.getAll());
    }

    /*=====超级无敌巨无霸三合一之添加股票信息=====*/
    @RequestMapping("/init")
    public ResultBean initStockMarket() {
        //获取方法运行开始时间
        long l = System.currentTimeMillis();
        //循环读取100支股票信息
        String model = "000000";
        String url = null;
        StringBuilder code = new StringBuilder(model);
        String timeSSS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Timestamp(System.currentTimeMillis()));
        String timeDay = new SimpleDateFormat("yyyy-MM-dd").format(new Timestamp(System.currentTimeMillis()));
        Stock stock=null;
        for (int i = 1; i <= 200; i++) {
            code.replace(code.length() - ("" + i).length(), code.length(), "" + i);
            //从接口获取数据
            url = "http://qt.gtimg.cn/q=sz" + code.toString();
            String method = HttpClientUtil.getMethod(url);
            String[] split = method.split("\"");
            String[] data = split[1].split("~");
            if (data.length == 1) {
                continue;
            }
            //获取股票基本信息（仅在第一次记录股票信息时）
            if("0".equals(data[6])){
                stock = new Stock(null, code.toString(), data[1]);
            }else {
                stock = new Stock(null, code.toString(), data[1],
                        Integer.parseInt(data[6]),
                        BigDecimal.valueOf(Double.parseDouble(data[37])),
                        BigDecimal.valueOf(Double.parseDouble(data[32])),
                        BigDecimal.valueOf(Double.parseDouble(data[45])));
            }
            //插入数据库
            stockService.add(stock);

            //获取开高低收信息（每次刷新页面都需要进行跟新）
            StockOhcl stockOhcl = new StockOhcl(null, code.toString(),
                    BigDecimal.valueOf(Double.parseDouble(data[5])),
                    BigDecimal.valueOf(Double.parseDouble(data[33])),
                    BigDecimal.valueOf(Double.parseDouble(data[4])),
                    BigDecimal.valueOf(Double.parseDouble(data[34])),
                    stock.getStockId(),
                    BigDecimal.valueOf(Double.parseDouble(data[3])),
                    timeSSS);
            //插入数据库
            stockOhclService.add(stockOhcl);

            //获取股票今日最高涨停和最低跌停（一天获取一次）
            StockStopPoint stockStopPoint = new StockStopPoint(null, stock.getStockId(), BigDecimal.valueOf(Double.parseDouble(data[47])), BigDecimal.valueOf(Double.parseDouble(data[48])), timeDay);
            //插入数据库
            stockStopPointService.add(stockStopPoint);
        }
        return new ResultBean(0, "初始化成功!", (System.currentTimeMillis() - l) / 1000);
    }

    /**
     * 用来查询并存储最新价格，仅查询，需要放于定时器中定时跟新价格
     * 获取数据库中所有股票的当前价格，并存放于redis中
     * @return
     */
    @RequestMapping("/getMarketPrice")
    public ResultBean getMarketPrice() {
        //获取所有股票
        List<Stock> stocks = stockService.getAll();
        Map<String,Double> marketprice=new HashMap<>();
        String url = null;
        for (int i = 0; i < stocks.size(); i++) {
            //循环查询所有股票当前信息
            //从接口获取数据
            url = "http://qt.gtimg.cn/q=sz" + stocks.get(i).getStockCode();
            String method = HttpClientUtil.getMethod(url);
            String[] split = method.split("\"");
            String[] data = split[1].split("~");
            marketprice.put(stocks.get(i).getStockCode(),Double.parseDouble(data[3]));
        }
        redisUtil.set("marketPrice",marketprice);
        return new ResultBean(0,"查询成功",JSON.toJSONString(marketprice));
    }

    /**
     * 从redis中取出map，仅获取
     * @return
     */
    @RequestMapping("/getprices")
    public ResultBean getPrices() {
        Map<String,Double> prices=(Map<String,Double>)redisUtil.get("marketPrice");
        return new ResultBean(0,"查询成功",prices);
    }

    @RequestMapping("/pageInit")
    public ResultBean pageInit(String stockCode) {
        //获取方法运行开始时间
        long l = System.currentTimeMillis();
        //循环读取100支股票信息
        String url = null;
        String timeSSS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Timestamp(System.currentTimeMillis()));
        String timeDay = new SimpleDateFormat("yyyy-MM-dd").format(new Timestamp(System.currentTimeMillis()));
        //从接口获取数据
        url = "http://qt.gtimg.cn/q=" + stockCode;
        String method = HttpClientUtil.getMethod(url);
        String[] split = method.split("\"");
        String[] data = split[1].split("~");
        //获取股票基本信息（仅在第一次记录股票信息时）
        Stock stock = new Stock(null, stockCode.toString(), data[1],
                Integer.parseInt(data[6]),
                BigDecimal.valueOf(Double.parseDouble(data[37])),
                BigDecimal.valueOf(Double.parseDouble(data[32])),
                BigDecimal.valueOf(Double.parseDouble(data[45])));
        //插入数据库
        //获取开高低收信息（每次刷新页面都需要进行跟新）
        StockOhcl stockOhcl = new StockOhcl(null, stockCode.toString(),
                BigDecimal.valueOf(Double.parseDouble(data[5])),
                BigDecimal.valueOf(Double.parseDouble(data[33])),
                BigDecimal.valueOf(Double.parseDouble(data[4])),
                BigDecimal.valueOf(Double.parseDouble(data[34])),
                stock.getStockId(),
                BigDecimal.valueOf(Double.parseDouble(data[3])),
                timeSSS);
        //插入数据库
        //获取股票今日最高涨停和最低跌停（一天获取一次）
        StockStopPoint stockStopPoint = new StockStopPoint(null, stock.getStockId(), BigDecimal.valueOf(Double.parseDouble(data[47])), BigDecimal.valueOf(Double.parseDouble(data[48])), timeDay);
        //插入数据库
        List<Object> list=new ArrayList<>();
        list.add(stock);
        list.add(stockOhcl);
        list.add(stockStopPoint);
        return new ResultBean(0, "获取数据信息成功!", list);
    }

}





















